package controller.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UserDao;
import factory.UserFactory;
import pojo.User;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			UserDao userDao = UserFactory.getInstance("userdaoimpl", UserDao.class);
			String uname = request.getParameter("uname");
			String upwd = request.getParameter("upwd");
			String noLogin = request.getParameter("noLogin");
			String code = request.getParameter("code");
			String sCode = (String) request.getSession().getAttribute("sCode");
			System.out.println("用户名"+uname+"\\密码"+upwd);
			PrintWriter out = response.getWriter();
			System.out.println("用户输入："+code+"\\sessionCode:"+sCode);
			if(!code.equalsIgnoreCase(sCode)){
				//out.println("<script>alert('验证码错误，验证码忽略大小写！');</script>");
				out.println("<script>alert('验证码错误！');self.location=document.referrer;</script>") ;
				return ;
//				request.getSession().setAttribute("msg", "验证码错误");
//				response.sendRedirect("view/login.jsp");
				//request.getRequestDispatcher("view/login.jsp").forward(request, response);
			}
			List<User> lists = userDao.getAllUser();
			for (User user : lists) {
				if(user.getUname().equals(uname) && user.getUpwd().equals(upwd)) {
					switch (noLogin) {
					case "3hour":
						setSession(request, "uname", uname, 3*60);
						break;
					case "3day":
						setSession(request, "uname", uname, 3*24*60);
						break;
					case "7day":
						setSession(request, "uname", uname, 7*24*60);
						break;
					default:
						setSession(request, "uname", uname, 3);
					}
					response.sendRedirect("view/index.jsp");
				}
			}
			out.println("<script>alert('登录失败，用户名或密码错误！');history.back();</script>") ;
		} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	protected void setSession(HttpServletRequest request, String key, String value, int timeNum) {
		HttpSession session = request.getSession();
		session.setAttribute(key, value);
		session.setMaxInactiveInterval(timeNum*60);
	}
}